﻿// add initializer
window.addEventListener("load", function (e) { GoJanusFFMenu.init(e); }, false);

function dump2(s) {
    dump(s + "\n");
}

var GoJanusFFMenu =
{
    init: function () {
        dump2("> init");
        var janusMenu = document.getElementById("gojanusff-menu");
        var menu = janusMenu.parentNode;

        if (menu)
            menu.addEventListener("popupshowing", function (e) { return GoJanusFFMenu.doContext(e); }, false);

        this.sbErrors = Components.classes["@mozilla.org/intl/stringbundle;1"]
						.getService(Components.interfaces.nsIStringBundleService)
						.createBundle("chrome://gojanusff/locale/errors.properties");

        dump2("< init");
    },
    doContext: function () {
        dump2("> doContext");

        // default - no hide menu
        var hideMenu = false;

        // check if menu shall be hidden on non RSDN links
        var prefs = Components.classes["@mozilla.org/preferences-service;1"].
					getService(Components.interfaces.nsIPrefBranch);

//        if (prefs.getBoolPref("gojanusff.showOnlyOnRsdnLinks") == true) {
//            // check link
//            var topicID = GoJanusFFMenu.getRsdnTopicID();
//            hideMenu = (topicID == null);
//        }

        // hide
        dump2("hiding menu=" + hideMenu);

        document.getElementById("gojanusff-sep").hidden = hideMenu;
        document.getElementById("gojanusff-menu").hidden = hideMenu;

        dump2("< doContext");

        return true;
    },
    getUrl: function () {
        // click was not on link
        if (!gContextMenu.onLink) {
            return null;
        }

        return gContextMenu.link;
    },
    getRsdnTopicID: function () {
        // click was not on link
        if (!gContextMenu.onLink) {
            return null;
        }

        return GoJanusFFMenu.getRsdnTopicIDFromURL(gContextMenu.link);
    },
    getRsdnTopicIDFromURL: function (url) {
        dump2("GetTopicID from url=" + url);
        try {
            if (url == null) {
                return;
            }
            // устарело
            // RegExp проверки на то, что ссылка принадлежит сайту RSDN
            // Варианты ссылок:
            // http://gzip.rsdn.ru/Forum/message/1130666.aspx
            // http://rsdn.ru/forum/?action=message&gid=5&mid=367
            // http://www.rsdn.ru/forum/message.asp?mid=8073
            // http://www.rsdn.ru/forum/?gid=3&mid=7755&tid=7444
            // http://gzip.rsdn.ru/Forum/Message.aspx?mid=1123201&only=1
            // http://gzip.rsdn.ru/Forum/?mid=975381
            // http://gzip.rsdn.ru/forum/message.1171387.aspx

            // new links
            // http://www.rsdn.ru/?forum/test/4306224.aspx
            // http://www.rsdn.ru/forum/humour/4304797.flat.aspx
            // janus://message/4306224
            // http://rsdn.ru/forum/flame.politics/4354735.flat.aspx

            //        (janus://message/\d+)|(http://(gzip\.|www\.)?rsdn\.ru/(\?)?forum/(\w+/|message/|\?action=message&gid=\d+&mid=|\?mid=|message\.aspx?\?mid=|\?gid=\d+&mid=|message\.)(\d+)(\.aspx)?)


            //var regex1 =                       new RegExp("http://(gzip\\.|www\\.)?rsdn\\.ru/forum/(message/|\\?action=message&gid=\\d+&mid=|\\?mid=|message\\.aspx?\\?mid=|\\?gid=\\d+&mid=|message\.)(\\d+)(\\.aspx)?", "gi");
            var regex1 = new RegExp("(janus://message/\\d+)|(http://(gzip\\.|www\\.)?rsdn\\.ru/(\\?)?forum/(\\w+/|message/|\\?action=message&gid=\\d+&mid=|\\?mid=|message\\.aspx?\\?mid=|\\?gid=\\d+&mid=|message\.)(\\d+)(\\.aspx)?)", "gi");

            //A RegExp method that tests for a match in a string. It returns true or false.
            if (regex1.test(url) == false) {
                return null;
            }

            dump2("Extracted TopicID=" + RegExp.$3);
            var found = url.match(regex1);
            alert("Extracted TopicID=" + RegExp.$1 + "1|\n" + RegExp.$2 + "2|\n" + RegExp.$3 + "3|\n" + found);

            return parseInt(RegExp.$3);
        }
        catch (e) {
            dump2("getRsdnTopicIDFromURL.exception: " + e);
        }
        return null;
    },
    doOpen: function () {
        //GoJanusFFMenu.doCmdForContextLink('go');
        GoJanusFFMenu.doCmdForContextLink('url');
    },
    doDownload: function () {
        GoJanusFFMenu.doCmdForContextLink('dlurl');
    },
    doDownloadAll: function () {
        try {
            var commands = [];
            var urlLength = 0;

            if (gContextMenu.link == null) {
                alert(this.sbErrors.GetStringFromName("select.link"));
                return;
            }
            var anchors = gContextMenu.link.ownerDocument.getElementsByTagName("A");

            for (var i = 0; i < anchors.length; i++) {
                //var topicID = GoJanusFFMenu.getRsdnTopicIDFromURL(anchors[i].href);
                var url = anchors[i].href;
                if (url == null || url.length == 0) {
                    continue;
                }

                // add topic to download
                commands.push("dlurl" + url);
                //take care of command line length
                if (urlLength > 1500) {
                    urlLength = 0;
                    //alert(commands);
                    GoJanusFFMenu.sendCommand(commands);
                    commands = [];
                    
                }
                urlLength += 5; //dlurl
                urlLength += url.length;
                //alert(urlLength);
                //alert(url.length);
                //break;
            }

            if (commands.length == 0) {
                throw Components.Exception("Nothing to download");
            }

            //alert(commands);
            GoJanusFFMenu.sendCommand(commands);

            alert(this.sbErrors.GetStringFromName("ok"));
        }
        catch (e) {
            alert(e);
        }
    },
    doCmdForContextLink: function (cmd) {
        dump2("doCmdForContextLink: " + cmd);

        try {
            //var topicID = GoJanusFFMenu.getRsdnTopicID();
            //if (topicID == null) {
            //    alert(this.sbErrors.GetStringFromName("unknown.url"));
            //    return;
            //}

            //GoJanusFFMenu.sendCommand([cmd + topicID]);
            var url = GoJanusFFMenu.getUrl()
            //var hint = gContextMenu.target.getAttribute('title');
            // text in UTF8
            //var hintUri = gContextMenu.linkText();
            // not found a way to send Unicode over DOS
            var hint = "";
            //CopyUTF16toUTF8(hintUni, hint);
            //var decoder = Components.classes["@mozilla.org/intl/utf8converterservice;1"].getService(Components.interfaces.nsIUTF8ConverterService);
            //hint =  decoder.convertStringToUTF8(hintUri, "WINDOWS-1251", true)
            //alert(hint);
            GoJanusFFMenu.sendCommand(["hint" + hint, cmd + url]);

            //if (cmd == 'download')
            //    alert(this.sbErrors.GetStringFromName("ok"));
        }
        catch (e) {
            alert(e);
        }
    },
    sendCommand: function (args) {
        // get 'components' directory 
        var file = Components.classes['@rsdn.ru/janus/mylocation;1']
			.createInstance(Components.interfaces.nsISupports)
			.wrappedJSObject.GetMyLocation();

        //alert(file);

        file.append("GoJanusCmd.exe");
        //alert(file);
        //alert(args);

        var process = Components.classes['@mozilla.org/process/util;1']
			.createInstance(Components.interfaces.nsIProcess); // Bugzilla@Mozilla – Bug 497821

        process.init(file);
        process.run(true, args, args.length);

        switch (process.exitValue) {
            case 0:
                break;
            case 1:
                throw this.sbErrors.GetStringFromName("generic");
            case 2:
                throw this.sbErrors.GetStringFromName("noJanus");
            case 3:
            default:
                throw this.sbErrors.GetStringFromName("generic");
        }
        process = null;
    }
}
